<template>
  <div class="my-upload">
    <h3>+</h3>
    <img v-if="imgUrl" :src="imgUrl" alt="" />
    <input type="file" @change="getFile" />
  </div>
</template>

<script>
import path from "path";
import { errorAlert } from "../utils/alert";
/* 
Event:
   sendFile 参数就是文件
方法:
   setImgUrl 参数是设置的图片地址
*/
export default {
  data() {
    return {
      imgUrl: "",
    };
  },
  methods: {
    // 选择图片
    getFile(e) {
      let file = e.target.files[0];
      // console.log(file);

      // 验证文件大小
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件最大2MB");
        return;
      }

      // 验证文件类型
      let extname = path.extname(file.name);
      let imgArr = [".png", ".jpg", ".jpeg", ".gif"];
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      // 生成一张图
      this.imgUrl = URL.createObjectURL(file);

      // 赋值给user.img (子传负将图片文件给父组建)
      this.$emit("sendFile", file);
    },
    setImgUrl(url) {
      this.imgUrl = url;
    },
  },
};
</script>

<style scoped lang="less">
@import "../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  position: relative;
  h3 {
    text-align: center;
    line-height: 100px;
  }
  input,
  img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
  input {
    opacity: 0;
  }
}
</style>